<template>
	<view>
		<cu-custom :isBack="true" :isFromOutside="isFromOutside">
			<block slot="backText">{{isFromOutside?'首页':'返回'}}</block>
			<block slot="content">{{navTitle}}</block>
		</cu-custom>
		<mescroll-body ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback" :up="upOption">
			<view v-for="(item,index) in dataList" :key="index">
				<active-post-item :showCircle="true" @clickTopic="clickCircleTopicAction(item.circle_topic)"
					@delete="deleteAction(index)" @report="reportAction(index)"
					:showDelete="circle.owner_id==userId||item.owner_id==userId||item.owner_id==userInfo.user_id||userInfo.owner_id==circle.owner_id||userInfo.role_id>0"
					@favorite="favoriteAction(index)" @praise="praiseAction(index)" @reward="rewardAction(index)"
					:index="index" @reply="replyComment" @loadMoreComment="loadMoreComment(index,item)"
					@expand="expandAction(index)" @commentAction="sendCommentAction(index,item)" :post="item"
					:circleOwnerId="circle.owner_id"
					@commentExpand="activeCommentExpand"
					></active-post-item>
			</view>
		</mescroll-body>
		<input-panel @onReplySuccess="onReplySuccess" @onCommentSuccess="onCommentSuccess"
			:originInfo="inputPanelOriginInfo" @blur="showInputPanel=false" title="写评论" doneBtn="发表" :autoFocus="true"
			v-if="showInputPanel" class="input-panel"></input-panel>
		<score-pay :userInfo="userInfo" :index="scorePostIndex" @chooseScore="chooseScoreAction"
			@hidden="showScorePay=false" v-if="showScorePay" ref="scorePay" class="input-panel"></score-pay>
		<view class="cu-modal" :class="form.modalStatus">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">{{formTitle}}</view>
					<view class="action" @tap="form.modalStatus=''">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="padding-xl flex justify-start" style="flex-direction: column;">
					<view class="flex justify-center align-center padding-bottom-lg" style="width: 100%;">
						<textarea v-if="form.modalStatus.length > 0"
							class="bg-white radius padding-top padding-left text-left" v-model="form.textInput"
							placeholder="请输入内容"></textarea>
					</view>
					<view class="action flex justify-center padding bg-white" style="width: 100%;">
						<button @tap="commitOperateAction" class="cu-btn round bg-blue" style="width: 90%;">提交</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";
	import ActivePostItem from '@/components/active-post-item.vue';
	import InputPanel from '@/components/input-panel.vue'
	import ScorePay from '@/components/score-pay.vue';
	import config from '@/api/config.js'
	import {
		getActivePostDetail,
		getActivePostCommentList,
		getMyActivePostList,
		getOtherActivePostList,
		rewardOther,
		praise,
		favoritePost,
		reportPost,
		deleteActivePost,
		getMyFavoriteActivePostList
	} from '@/api/api.js'
	import {
		getTagColorForRole,
		cutDateFromDateTime,
		getTimeDistance
	} from '@/api/utils.js'
	import {
		checkLogin
	} from '@/js_sdk/checkLogin.js'
	import {
		isLogin,
		getUserInfo,
		setUserInfo,
		updateUserInfo
	} from '@/api/auth.js'
	export default {
		mixins: [MescrollMixin],
		components: {
			ActivePostItem,
			InputPanel,
			ScorePay
		},
		computed: {
			formTitle() {
				if (this.form.isPasswordJoin) {
					return '请输入入圈口令'
				}
				if (this.form.isApply) {
					return '请输入加圈理由'
				}
				return '举报'
			},
			navTitle() {
				if (this.mode == 'my') {
					return '我的动态'
				}
				if (this.mode == 'my_fav') {
					return '收藏动态'
				}
				return '动态详情'
			}
		},
		data() {
			return {
				isFromOutside: false,
				upOption: {
					page: {
						size: 10 // 每页数据的数量,默认10
					},
					textNoMore: config.customNoMore,
					noMoreSize: 1, // 配置列表的总数量要大于等于5条才显示'-- END --'的提示
					empty: {
						tip: '暂无相关数据'
					}
				},
				userId: null,
				mode: '',
				dataList: [],
				postId: null,
				form: {
					isPasswordJoin: false,
					isApply: false,
					modalStatus: '',
					reportPostId: '',
					textInput: '',
				},
				userInfo: getUserInfo(),
				scorePostIndex: -1,
				showScorePay: false,
				inputPanelOriginInfo: null,
				showInputPanel: false,
			}
		},
		onPageScroll() {
			uni.$emit('ActivePostListDidSroll')
		},
		onLoad(options) {
			if (options.postId !== null && options.postId !== undefined) {
				this.postId = options.postId
			}
			if (options.mode !== null && options.mode !== undefined) {
				this.mode = options.mode
				if (this.mode == 'other' && options.userId !== null && options.userId !== undefined) {
					this.userId = options.userId
				}
			}
			if (options.outside !== null && options.outside !== undefined) {
				this.isFromOutside = true
			}
		},
		methods: {
			activeCommentExpand(passParams)
			{
				let postIndex = passParams[0]
				let commentIndex = passParams[1]
				let status = this.dataList[postIndex].comment_list[commentIndex].is_expand? false:true
				this.dataList[postIndex].comment_list[commentIndex].is_expand = status
			},
			onShareAppMessage(res) {
				if (res.from && res.from == "button") {
					if (res.target.dataset !== null && res.target.dataset !== undefined && res.target.dataset.postid !==
						undefined) {
						let dataset = res.target.dataset
						let circle = dataset.circle
						let author = dataset.author
						let postId = dataset.postid
						let title = "快来围观“@" + author + "”在圈子《" + circle + "》发表的精彩动态吧~"
						return {
							title: title,
							path: '/pages/lessuse/active-list/active-list?postId=' + postId + '&outside=1'
						}
					}
				}
				return {
					title: '快来TopicQ发现各种圈子的有趣内容吧～',
					path: '/pages/circle/circle?outside=1'
				}
			},
			onShareTimeline(res) {
				if (res.from && res.from == "button") {
					if (res.target.dataset !== null && res.target.dataset !== undefined && res.target.dataset.postid !==
						undefined) {
						let dataset = res.target.dataset
						let circle = dataset.circle
						let author = dataset.author
						let postId = dataset.postid
						let title = "快来围观“@" + author + "”在圈子《" + circle + "》发表的精彩动态吧~"
						return {
							title: title,
							path: '/pages/lessuse/active-list/active-list?postId=' + postId + '&outside=1'
						}
					}
				}
				return {
					title: '快来TopicQ发现各种圈子的有趣内容吧～',
					path: '/pages/circle/circle?outside=1'
				}
			},
			getDataList(pageIndex, pageSize) {
				if (this.mode == 'my_fav') {
					getMyFavoriteActivePostList(pageIndex, pageSize).then(res => {
						res.data.list.forEach(item => {
							item.is_expand = false
							item.show_time = getTimeDistance(item.created_at)
							if (item.rich_content && item.rich_content.length > 0) {
								item.rich_content = JSON.parse(item.rich_content)
								item.is_rich_content = true
							}
							if(item.comment_list&&item.comment_list.length>0) {
								item.comment_list.forEach(comment=>{
									comment.is_expand = false
								})
							}
						})
						let pageList = res.data.list
						if (pageIndex == 0) {
							this.dataList = pageList
						} else {
							this.dataList = this.dataList.concat(pageList);
						}
						console.log('page length:' + pageList.length)
						let hasNext = pageList.length >= pageSize
						if (this.mescroll) {
							this.mescroll.endSuccess(pageList.length, hasNext);
						}
					}).catch(error => {
						uni.hideLoading()
						if (this.mescroll) {
							this.mescroll.endErr()
						}
					})
					return
				}
				if (this.mode == 'my') {
					getMyActivePostList(pageIndex, pageSize).then(res => {
						res.data.list.forEach(item => {
							item.is_expand = false
							item.show_time = getTimeDistance(item.created_at)
							if (item.rich_content && item.rich_content.length > 0) {
								item.rich_content = JSON.parse(item.rich_content)
								item.is_rich_content = true
							}
							if(item.comment_list&&item.comment_list.length>0) {
								item.comment_list.forEach(comment=>{
									comment.is_expand = false
								})
							}
						})
						let pageList = res.data.list
						if (pageIndex == 0) {
							this.dataList = pageList
						} else {
							this.dataList = this.dataList.concat(pageList);
						}
						console.log('page length:' + pageList.length)
						let hasNext = pageList.length >= pageSize
						if (this.mescroll) {
							this.mescroll.endSuccess(pageList.length, hasNext);
						}
					}).catch(error => {
						uni.hideLoading()
						if (this.mescroll) {
							this.mescroll.endErr()
						}
					})
				}
			},
			downCallback() {
				if (this.mescroll) {
					this.mescroll.resetUpScroll()
				}
			},
			upCallback(page) {
				let pageIndex = page.num - 1
				if (this.mode == 'my' || this.mode == 'other' || this.mode == 'my_fav') {
					this.getDataList(pageIndex, page.size)
					return
				}
				this.getActiveDetail()
			},
			getActiveDetail() {
				//通过postId拉取
				uni.showLoading({
					title: '正在加载...'
				})
				getActivePostDetail(this.postId).then(res => {
					res.data.forEach(item => {
						item.is_expand = false
						item.show_time = getTimeDistance(item.created_at)
						if (item.rich_content && item.rich_content.length > 0) {
							item.rich_content = JSON.parse(item.rich_content)
							item.is_rich_content = true
						}
						if(item.comment_list&&item.comment_list.length>0) {
							item.comment_list.forEach(comment=>{
								comment.is_expand = false
							})
						}
					})
					this.dataList = res.data
					let hasNext = false
					uni.hideLoading()
					if (this.mescroll) {
						this.mescroll.endSuccess(res.data.length, hasNext);
					}
				}).catch(error => {
					uni.hideLoading()
					if (this.mescroll) {
						this.mescroll.endErr()
					}
				})
			},
			commitOperateAction() {
				if (this.form.textInput.length == 0) {
					uni.showToast({
						icon: 'none',
						title: '请输入举报理由!'
					})
					return
				}
				uni.showLoading({
					title: '正在提交...'
				})
				reportPost(this.form.reportPostId, this.form.textInput).then(res => {
					uni.hideLoading()
					uni.showToast({
						title: '举报已提交'
					})
					this.form.modalStatus = null
				}).catch(error => {
					uni.hideLoading()
					uni.showToast({
						icon: 'none',
						title: '提交失败'
					})
				})
			},
			realDeleteActivePost(index) {
				uni.showLoading({
					title: '正在删除...'
				})
				let postId = this.dataList[index].post_id
				deleteActivePost(postId, this.circle.circle_id).then(res => {
					uni.hideLoading()
					uni.showToast({
						title: '删除成功!'
					})
					this.dataList.splice(index, 1)
				}).catch(error => {
					uni.hideLoading()
				})
			},
			deleteAction(index) {
				let that = this
				uni.showModal({
					title: '动态删除提示!',
					content: '动态删除后将无法找回，是否继续?',
					cancelText: '手滑了',
					confirmText: '确认删除',
					success: (res) => {
						if (res.confirm) {
							that.realDeleteActivePost(index)
						}
					}
				})
			},
			reportAction(index) {
				this.form.reportPostId = this.dataList[index].post_id
				this.form.modalStatus = 'show'
			},
			praiseAction(index) {
				let post = this.dataList[index]
				let oldStatus = post.is_praise
				let newStatus = post.is_praise == 1 ? 0 : 1
				this.dataList[index].is_praise = newStatus
				praise(post.post_id).then(res => {
					this.dataList[index].is_praise = newStatus
					if (newStatus == 1) {
						this.dataList[index].praise_count++
					} else {
						this.dataList[index].praise_count--
					}
					this.$forceUpdate()
				}).catch(error => {
					this.dataList[index].is_praise = oldStatus
				})
			},
			favoriteAction(index) {
				let post = this.dataList[index]
				let oldStatus = post.is_favorite
				let newStatus = post.is_favorite == 1 ? 0 : 1
				this.dataList[index].is_favorite = 1
				favoritePost(post.post_id).then(res => {
					this.dataList[index].is_favorite = newStatus
					if (newStatus == 1) {
						this.dataList[index].favorite_count++
					} else {
						this.dataList[index].favorite_count--
					}
					this.$forceUpdate()
				}).catch(error => {
					this.dataList[index].is_favorite = oldStatus
				})
			},
			chooseScoreAction(params) {
				let score = params[0]
				let index = params[1]
				let postId = this.dataList[index].post_id
				uni.showLoading({
					title: '正在提交...'
				})
				rewardOther(postId, score).then(res => {
					uni.hideLoading()
					uni.showToast({
						icon: 'none',
						title: '打赏成功'
					})
					this.showScorePay = false
					updateUserInfo()
					setTimeout(() => {
						this.userInfo = getUserInfo()
					}, 300)
				}).catch(error => {

				})
			},
			rewardAction(index) {
				let otherUserId = this.dataList[index].author.user_id
				if (otherUserId == this.userInfo.user_id) {
					uni.showToast({
						icon: 'none',
						title: '不要自己打赏自己哦~'
					})
					return
				}
				this.showScorePay = true
				this.scorePostIndex = index
			},
			onReplySuccess(params) {
				let postIndex = params[0]
				let comment = params[1]
				let commentList = [comment]
				this.dataList[postIndex].comment_count++
				this.dataList[postIndex].comment_list = commentList.concat(this.dataList[postIndex].comment_list)
			},
			onCommentSuccess(params) {
				let postIndex = params[0]
				let comment = params[1]
				let commentList = [comment]
				this.dataList[postIndex].comment_count++
				this.dataList[postIndex].comment_list = commentList.concat(this.dataList[postIndex].comment_list)
			},
			replyComment(params) {
				let post = this.dataList[params[0]]
				let comment = post.comment_list[params[1]]
				let info = {
					'postId': post.post_id,
					'commentId': comment.comment_id,
					'replyUser': comment.author.nickname,
					'postIndex': params[0]
				}
				this.inputPanelOriginInfo = info
				this.showInputPanel = true
			},
			loadMoreComment(index, post) {
				if (post.comment_load_finish) {
					return
				}
				let lastCommentId = post.comment_list[post.comment_list.length - 1].comment_id
				let num = 5
				getActivePostCommentList(post.post_id, lastCommentId, num).then(res => {
					post.comment_list = post.comment_list.concat(res.data)
					if (post.comment_list.length >= post.comment_count) {
						post.comment_load_finish = true
					}
				}).catch(error => {

				})
			},
			expandAction(index) {
				this.dataList[index].is_expand = !this.dataList[index].is_expand
			},
			sendCommentAction(index, post) {
				let info = {
					'postId': post.post_id,
					'postIndex': index
				}
				this.inputPanelOriginInfo = info
				this.showInputPanel = true
			},
		},
	}
</script>

<style scoped>
	.input-panel {
		position: fixed;
		height: 100%;
		width: 100%;
		bottom: 0%;
		z-index: 9999;
	}
</style>
